/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.encontreventos.webapp.controle;

import java.io.Serializable;
import java.util.Map;
import java.util.Properties;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import org.brickred.socialauth.AuthProvider;
import org.brickred.socialauth.Profile;
import org.brickred.socialauth.SocialAuthConfig;
import org.brickred.socialauth.SocialAuthManager;
import org.brickred.socialauth.util.AccessGrant;
import org.brickred.socialauth.util.SocialAuthUtil;

/**
 *
 * @author Eduardo
 */
@ManagedBean(name = "userSession")
@SessionScoped
public class UserSessionBean implements Serializable {

    // Objeto que possui as rotinas do SocialAuth, biblioteca responsável para o login em diferentes provedores
    private SocialAuthManager manager;
    private String originalURL;
    // Texto para identificar o provedor (Facebook, G+)
    private String providerID;
    // Perfil do usuário no provedor
    private Profile profile;

    // ID do aplicativo no facebook
    private final String APP_IDD = "205983009590594";
    // Código da chave secreta do aplicativo
    private final String APP_SECRET = "4875e27f519fafa28e88c639eb67d4aeT";

    /**
     * @return the manager
     */
    public SocialAuthManager getManager() {
        return manager;
    }

    /**
     * @param manager the manager to set
     */
    public void setManager(SocialAuthManager manager) {
        this.manager = manager;
    }

    /**
     * @return the originalURL
     */
    public String getOriginalURL() {
        return originalURL;
    }

    /**
     * @param originalURL the originalURL to set
     */
    public void setOriginalURL(String originalURL) {
        this.originalURL = originalURL;
    }

    /**
     * @return the providerID
     */
    public String getProviderID() {
        return providerID;
    }

    /**
     * @param providerID the providerID to set
     */
    public void setProviderID(String providerID) {
        this.providerID = providerID;
    }

    /**
     * @return the profile
     */
    public Profile getProfile() {
        return profile;
    }

    /**
     * @param profile the profile to set
     */
    public void setProfile(Profile profile) {
        this.profile = profile;
    }

    public void socialConect() throws Exception {
        // Aplicar as configurações do aplicativo para acesso as informações do usuário 
        Properties props = System.getProperties();
        props.put("graph.facebook.com.consumer_key", this.APP_IDD);
        props.put("graph.facebook.com.consumer_secret", this.APP_SECRET);

        SocialAuthConfig config = SocialAuthConfig.getDefault();
        config.load(props);

        // Aplicar a configuração do aplicativo
        this.manager = new SocialAuthManager();
        this.manager.setSocialAuthConfig(config);

        String successURL = "http://encontreventos.com/EncontreventosWebApp/sucesso.jsf";
        String authenticationURL = this.manager.getAuthenticationUrl("facebook", successURL);
        FacesContext.getCurrentInstance().getExternalContext().redirect(authenticationURL);
    }

    public void pullUserInfo() {
        try {
            // Obter os dados do provedor
            ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
            HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
            
            Map map = SocialAuthUtil.getRequestParametersMap(request);
    
            if (this.getManager() != null) {
                AccessGrant access = this.manager.createAccessGrant(this.providerID, (String) map.get("code"), "http://encontreventos.com/EncontreventosWebApp/sucesso.jsf");
                AuthProvider provider = this.manager.connect(access);
                this.profile = provider.getUserProfile();
                // Redirecionar para a página de retorno, antes de realizar o login
                FacesContext.getCurrentInstance().getExternalContext().redirect(getOriginalURL());
            } else {
                FacesContext.getCurrentInstance().getExternalContext().redirect(externalContext.getRequestContextPath() + "index.xhtml");
            }
        } catch (Exception ex) {
            System.out.println("UserSession - Exception: " + ex.toString());
        }
    }
}
